<template>
  <div>
    <van-nav-bar :title="t('抓码比对.拣货')" left-arrow @click-left="onClickLeft" placeholder fixed/>

    <div v-if="!hasDown">
      <van-form style="margin-top: 35vh">
        <scanning v-if="false" @keydownEnter="handleScanStart" @blur="handleScanStartBlur" :placeholder="t('抓码比对.请扫描开始SI条码')" :isFocus="true"
                  style="margin-bottom: 20px; height: 50px"></scanning>
        <scanning v-if="false" @keydownEnter="handleScanEnd" @blur="handleScanEndBlur" ref="endSiCodeRef" :placeholder="t('抓码比对.请扫描结束SI条码')"
        style="height: 50px"></scanning>
        <scanning @keydownEnter="handleScan" @blur="handleScanBlur" :placeholder="t('抓码比对.请扫描拣货单条码')" :isFocus="true"
                            style="margin-bottom: 20px; height: 50px"></scanning>
        <div style="margin: 16px;">
          <van-button block type="primary" @click="downOrder">{{t('抓码比对.开始拣货')}}</van-button>
        </div>
      </van-form>
    </div>

    <div v-else>
      <van-form style="margin-bottom: 10vh">
        <!-- <scanning ref="providerTrackingNoStartRef" @keydownEnter="handleScanProviderTrackingNoStart"
                  :placeholder="t('抓码比对.请扫描物流商单号')"
                  style="height: 50px"></scanning> -->
        <van-cell :title="t('抓码比对.拣货单号')" :value="startSiCode"></van-cell>
        <van-cell :title="t('抓码比对.物流商单号')" :value="orderForm ? orderForm.providerTrackingNo : null"></van-cell>
        <van-cell class="exp">
          <template #title>
            <span class="van-multi-ellipsis--l1">{{ t('抓码比对.件数') }}</span>
          </template>
          <template #value>
            <span class="font-size1 van-color-text-assist">
              {{ `${totalNum||0}/${orderForm ? orderForm.totalNum||0 : 0}` }}
            </span>
            <span class="font-size2 van-color-text-assist">
              {{ orderForm ? orderForm.orderVoteTypeName : null }}
            </span>
          </template>
        </van-cell>
        <van-cell class="exp">
          <template #title>
            <span class="van-multi-ellipsis--l1">{{ t('抓码比对.SKU种类') }}</span>
          </template>
          <template #value>
            <span class="font-size1 van-color-text-assist">
              {{ `${skuNum||0}/${orderForm ? orderForm.skuNum||0 : 0}` }}
            </span>
            <span style="opacity: 0;" class="font-size2 van-color-text-assist">
              {{ orderForm ? orderForm.orderVoteTypeName : null }}
            </span>
          </template>
        </van-cell>

        <van-cell :title="t('抓码比对.库位')" :value="goodsForm ? goodsForm.locationCode : null" style="margin-top: 10px"></van-cell>
        <van-cell :title="t('抓码比对.SKU')" :value="goodsForm ? goodsForm.skuCode : null"></van-cell>
        <van-cell :title="t('抓码比对.数量')" :value="goodsForm ? goodsForm.goodsNum : null"></van-cell>
        <van-cell :title="t('抓码比对.包材')" :value="goodsForm ? goodsForm.pack : null"></van-cell>

        <scanning ref="containerCodeRef" @keydownEnter="handleScanContainerCode" :placeholder="t('抓码比对.请扫描流转箱号')"
                  style="height: 50px; display: none"></scanning>
        <div style="display: flex; align-items: center">
          <scanning ref="skuCodeRef" @keydownEnter="handleScanSkuCode" :placeholder="t('抓码比对.请扫描SKU')"
                    style="height: 50px; width: 75vw"></scanning>
          <div style="background: white; width: 20vw; height: 50px; color: #b2acac">
            <div v-if="goodsForm ? goodsForm.scanNum : null" style="text-align: center; line-height: 50px;">
              {{ goodsForm ? goodsForm.scanNum : null }}
            </div>
            <div v-else style="text-align: center; line-height: 50px;">
              {{t('抓码比对.扫描数量')}}
            </div>
          </div>
        </div>
        <scanning ref="providerTrackingNoEndRef" v-if="false" @keydownEnter="handleScanProviderTrackingNoEnd"
                  :placeholder="t('抓码比对.请扫描物流商单号')"
                  style="height: 50px"></scanning>
        <div style="display: flex; width: 100%; justify-content: space-around;">
          <van-icon @click="onLeft" name="arrow-left" size="30px" style="background-color: #00b7ff; padding: 5px; border-radius: 20px;" color="white"/>
          <van-icon @click="onRight" name="arrow" size="30px" style="background-color: #00b7ff; padding: 5px; border-radius: 20px;" color="white" />
        </div>
        <van-popup
            v-model:show="showBottom"
            position="bottom"
            :style="{ height: '70vh' }"
        >
          <van-button type="success" size="small" style="width: 3rem" @click="orderUploadSubmit">{{t('抓码比对.上传')}}</van-button>
          <van-field>
            <template #input>
              <van-col span="3" style="text-align: center">
                <van-checkbox v-model="allCheckbox" @click="selectionAll"></van-checkbox>
              </van-col>
              <van-col span="11" style="text-align: center">
                {{t('抓码比对.物流商单号')}}
              </van-col>
              <van-col span="5" style="text-align: center">
                {{t('抓码比对.总件数')}}
              </van-col>
              <van-col span="5" style="text-align: center">
                {{t('抓码比对.状态')}}
              </van-col>
            </template>
          </van-field>
          <div style="height: 75%; overflow: auto">
            <van-checkbox-group v-model="selection">
              <van-field v-for="(item, index) in orderFormList" :key="index">
                <template #input>
                  <van-col span="3" style="text-align: center">
                    <van-checkbox :name="item.orderId"></van-checkbox>
                  </van-col>
                  <van-col span="11" style="text-align: center">
                    {{ item.providerTrackingNo }}
                  </van-col>
                  <van-col span="5" style="text-align: center">
                    {{ item.totalNum }}
                  </van-col>
                  <van-col span="5" :style="{
                    color: !item.pickingStatus || item.pickingStatus === 'N' ? 'red' : 'green',
                    textAlign: 'center'
                  }">
                    {{ item.pickingStatus || "N" }}
                  </van-col>
                </template>
              </van-field>
            </van-checkbox-group>
          </div>
        </van-popup>
        <div style="position: absolute; bottom: 0;display: flex; width: 100%;">
          <van-button block type="primary" @click="orderSubmit" style="height: 9vh">{{t('抓码比对.确认')}}</van-button>
          <van-button block type="warning" @click="orderUpload" style="height: 9vh">{{t('抓码比对.等待上传')}}（{{ orderFormList.length }}）</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import Scanning from "@/views/components/Scanning/index.vue";
import { useI18n } from "vue-i18n";
import { postRequest, scanSuccess, scanFail } from "@/api";
import { AppToast } from "@/utils/appToast";
import { Ref, nextTick } from "vue";

const { t } = useI18n();

const startSiCode = ref(null)
const endSiCode = ref(null)
const hasDown = ref(false)
const endSiCodeRef = ref(null)
// const providerTrackingNoStartRef = ref(null)
const containerCodeRef = ref(null)
const skuCodeRef = ref(null)
// const providerTrackingNoEndRef = ref(null)

interface OrderForm {
  orderId: number,
  orderNo: string,
  providerTrackingNo: string,
  goodsNumTotal: number,
  orderVoteType: number,
  orderVoteTypeName: string,
  skuCategoryNum: number,
  outboundOrderGraspingCodeGoodsList: OrderGoodsForm[],
  totalNum: number,
  skuNum: number,
  pickingStatus: string,
  siCode: string,
}

interface OrderGoodsForm {
  locationCode: string,
  locationPickSort: number,
  containerCode: string,
  skuCode: string,
  goodsNum: number,
  pack: string,
  scanNum: number,
  pickingStatus: string,
  skuId: number,
}

let orderFormList: OrderForm[] = []
let skuNum = 0
let totalNum = 0
let index = 0
const orderForm: Ref<OrderForm> = ref(null)
const goodsForm: Ref<OrderGoodsForm> = ref(null)
const showBottom = ref(false)
const allCheckbox = ref(false)
const selection = ref([])
const onClickLeft = () => history.back();
const handleScanStart = (value) => {
  startSiCode.value = value;
  endSiCodeRef.value.setFocus()
};
const handleScan = (value) => {
  startSiCode.value = value;
  downOrder();
};
const handleScanStartBlur = (value) => {
  startSiCode.value = value;
};
const handleScanBlur = (value) => {
  startSiCode.value = value;
};
const handleScanEnd = (value) => {
  endSiCode.value = value;
  downOrder();
};
const handleScanEndBlur = (value) => {
  endSiCode.value = value;
};
const selectionAll = () => {
  if (allCheckbox.value) {
    selection.value = orderFormList.map(d => d.orderId);
  } else {
    selection.value = []
  }
}
const downOrder = () => {
  if (undefined !== startSiCode.value && null !== startSiCode.value && "" !== startSiCode.value) {
    postRequest("/outbound/outBoundOrder/getSiCode", {
      siCode: startSiCode.value
    }).then(res => {
      if (res?.data?.isAllowedPicking === false) {
        scanFail()
        AppToast(t("抓码比对.拣货单拣货已完成请勿重复扫描"), "fail")
        return;
      }
      if (!res.data || !res.data?.orderList || res.data?.orderList?.length === 0) {
        scanFail()
        AppToast(t("抓码比对.无法获取订单信息"), "fail")
        return;
      }
      scanSuccess()
      orderFormList = res.data?.orderList?.filter(item => item.pickingStatus !== 'Y') || []
      hasDown.value = true
      index = 0;
      nextTick(() => {
        handleScanProviderTrackingNoStart(orderFormList[index].providerTrackingNo);
      })
      setTimeout(() => {
        // providerTrackingNoStartRef.value.setFocus()
      }, 50)
    }).catch(() => {
      scanFail()
    })
  }
};
const handleScanProviderTrackingNoStart = (value) => {
  const order = orderFormList.find(d => d.providerTrackingNo === value);
  if (!order) {
    AppToast(t("抓码比对.未找到订单或已扫描完毕"), "fail")
    // providerTrackingNoStartRef.value.setValue(undefined)
    return
  }

  orderForm.value = order

  if (!order.outboundOrderGraspingCodeGoodsList
      || order.outboundOrderGraspingCodeGoodsList.length === 0) {
    AppToast(t("抓码比对.无商品信息"), "fail")
    // providerTrackingNoStartRef.value.setValue(undefined)
    return
  }

  goodsForm.value = order.outboundOrderGraspingCodeGoodsList[0]
  goodsForm.value.scanNum = 0;
  totalNum = 0
  skuNum = 0
  // containerCodeRef.value.setFocus()
  // containerCodeRef.value.setValue(undefined)
  // skuCodeRef.value.setValue(undefined)
  skuCodeRef.value.setFocus()
  skuCodeRef.value.setValue(undefined)
  containerCodeRef.value.setValue(goodsForm.value.containerCode)
};
const handleScanContainerCode = (value) => {
  if (goodsForm.value.containerCode !== value) {
    scanFail()
    AppToast(t("抓码比对.流转箱号不正确"), "fail")
    containerCodeRef.value.setValue(undefined)
    return
  }
  scanSuccess()
  AppToast(t("抓码比对.流转箱号扫描成功"), "success")
  skuCodeRef.value.setFocus()
};
const handleScanSkuCode = (value) => {
  if (goodsForm.value.skuCode !== value) {
    scanFail()
    AppToast(t("抓码比对.SKU不正确"), "fail")
    skuCodeRef.value.setValue(undefined)
    return
  }
  if (goodsForm.value.scanNum === goodsForm.value.goodsNum) {
    scanFail()
    AppToast(t("抓码比对.SKU已足够"), "fail")
    skuCodeRef.value.setValue(undefined)
    return
  }
  scanSuccess()
  AppToast(t("抓码比对.SKU扫描成功"), "success")
  goodsForm.value.scanNum = goodsForm.value.scanNum + 1
  totalNum = totalNum + 1
  if (goodsForm.value.scanNum === goodsForm.value.goodsNum) {
    goodsForm.value.pickingStatus = 'Y'
    skuNum = skuNum + 1
  } else {
    skuCodeRef.value.setValue(undefined)
    return;
  }

  const goodsList: OrderGoodsForm[] = orderForm.value.outboundOrderGraspingCodeGoodsList
  const goods = goodsList.find(d => d.pickingStatus !== 'Y');
  if (goods) {
    goodsForm.value = goods
    goodsForm.value.scanNum = 0;
    // containerCodeRef.value.setFocus()
    // containerCodeRef.value.setValue(undefined)
    // skuCodeRef.value.setValue(undefined)
    skuCodeRef.value.setFocus()
    skuCodeRef.value.setValue(undefined)
    containerCodeRef.value.setValue(goodsForm.value.containerCode)
    return;
  }
  // providerTrackingNoEndRef.value.setFocus()
};
const handleScanProviderTrackingNoEnd = (value) => {
  if (orderForm.value.providerTrackingNo !== value) {
    AppToast(t("物流商号不匹配"), "fail")
    // providerTrackingNoEndRef.value.setValue(undefined)
    return
  }
  if (orderForm.value.totalNum !== totalNum) {
    AppToast(t("抓码比对.产品未扫描完毕"), "fail")
    // providerTrackingNoEndRef.value.setValue(undefined)
    return
  }
  AppToast(t("抓码比对.扫描完毕"), "success")
  // providerTrackingNoEndRef.value.setBlur()
};
const orderSubmit = () => {
  if (orderFormList?.length > 0) {
    if(!orderFormList[index].outboundOrderGraspingCodeGoodsList?.find(item => item.scanNum !== item.goodsNum)) {
      orderForm.value.pickingStatus = "Y";
      const orderN = orderFormList.find(d => d.pickingStatus !== "Y");
      // providerTrackingNoStartRef.value.setValue(undefined)
      containerCodeRef.value.setValue(undefined)
      skuCodeRef.value.setValue(undefined)
      orderForm.value = null
      goodsForm.value = null
      skuNum = 0
      totalNum = 0
      if (orderN) {
        // providerTrackingNoStartRef.value.setFocus()
        if (index < orderFormList.length - 1) {
          index++;
          handleScanProviderTrackingNoStart(orderFormList[index].providerTrackingNo);
        }
      }
    } else {
      AppToast('拣货数量与订单sku数量不一致', 'fail');
    }
  }
}
const orderUpload = () => {
  showBottom.value = true
}
const onLeft = () => {
  if (index <= 0) {
    AppToast(t("已经是第一个了"), "success");
    return;
  }
  index--;
  handleScanProviderTrackingNoStart(orderFormList[index].providerTrackingNo);
}
const onRight = () => {
  if (index >= orderFormList.length - 1) {
    AppToast(t("已经是最后一个了"), "success");
    return;
  }
  index++;
  handleScanProviderTrackingNoStart(orderFormList[index].providerTrackingNo);
}
const orderUploadSubmit = () => {
  if (!selection.value || selection.value.length === 0) {
    AppToast(t("抓码比对.请选择订单"), "fail")
    return
  }
  for (let i = 0; i < selection.value.length; i++) {
    const order = orderFormList.find(d => d.orderId === selection.value[i]);
    if (order) {
      if (!order.pickingStatus || order.pickingStatus === "N") {
        AppToast(t("抓码比对.有订单状态为N_不能上传"), "fail")
        return
      }
    } else {
      AppToast(t("抓码比对.选中订单不存在"), "fail")
      return
    }
  }
  let selectedOrderList = orderFormList.filter(item => selection.value?.includes(item.orderId));
  let selectedInfo = [];
  for (let i = 0; i < selectedOrderList.length; i++) {
    for (let j = 0; j < selectedOrderList[i].outboundOrderGraspingCodeGoodsList.length; j++) {
      selectedInfo.push({
        orderId: selectedOrderList[i].orderId,
        quantity: selectedOrderList[i].outboundOrderGraspingCodeGoodsList[j].goodsNum,
        sku: selectedOrderList[i].outboundOrderGraspingCodeGoodsList[j].skuCode,
        skuId: selectedOrderList[i].outboundOrderGraspingCodeGoodsList[j].skuId
      })
    }
  }

  postRequest("/outbound/outBoundOrder/setOrderStatusPicked", {
    orderSkuAddDtoList: selectedInfo
  }).then(() => {
    AppToast(t("抓码比对.上传成功"), "success")
    for (let i = orderFormList.length - 1; i >= 0; i--) {
      if (selection.value.includes(orderFormList[i].orderId)) {
        orderFormList.splice(i, 1);
      }
    }
    showBottom.value = false
    selection.value = []
    allCheckbox.value = false
  })
}
</script>

<style scoped lang="less">
:deep(.van-cell) {
  font-size: 1rem;
  &.exp {
    .van-cell__value {
      flex: 2;
      .font-size2 {
        display: inline-block;
        margin-left: 55px;
        background: #4bd863;
        color: white;
        padding: 0px 15px;
        border-radius: 5px;
      }
    }
  }
}

:deep(.van-nav-bar__title) {
  font-size: 1rem;
  font-weight: 500;
  color: white;
}

:deep(.van-nav-bar__content) {
  background: #1b82d2;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.van-cell__label) {
  font-size: 1rem;
}
</style>
